import 'dart:async';
import 'dart:collection';

import 'package:FineArt/components/horizon_scroll.dart';
import 'package:FineArt/components/rounded_text_with_del.dart';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/core/widget/grid/grid_staggered_item_photo.dart';
import 'package:FineArt/page/home/components/module_filter.dart';
import 'package:FineArt/page/imageview/BookPreview.dart';
import 'package:FineArt/page/imageview/ImagePreview.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class BookContentListPage extends StatefulWidget {
  final Resource resource;
  ResourceInfo0 info;

  BookContentListPage({this.resource, this.info});

  static void JumpToBookContentList(
      Resource resource, BuildContext context, bool fromFavorite) {
    ResourceApi().resourceDetail(resource.id, resource.type).then((res) {
      if (res.code == 200) {
        if (res.data.type == 0 || res.data.type == 5000) //图书
        {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            if(resource.title==null){
              resource.title = res.data.title;
            }
            return BookContentListPage(resource: resource, info: res.data.info);
          }));
        }
      }
    });
  }

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _BookContentListPageState(
        this.resource, this.info.url, this.info.totalpages);
  }
}

class _BookContentListPageState extends State<BookContentListPage> {
  final Resource _module;
  final String baseUrl;
  int totalPage;
  EasyRefreshController _controller = EasyRefreshController();

  _BookContentListPageState(this._module, this.baseUrl, this.totalPage);

  List<Category> default_categories = [];
  List<Resource> resources = [];
  int currentPage = 0;
  String currentPath = "";
  String currentFilter = "";
  int currentPid = 0;

  bool isFilter = false;
  String confirmKey;
  String currentCategoryLabel;
  Category currentCategory;

  double currentScrollOffset = 0; //for categories

  MoreFilterGroup filterGroupRoot;

  List<MoreFilterGroup> filterGroups = [];

  void _get_default_categories() {
    ModuleApi().categories(_module.id, _module.id).then((res) {
      if (!this.mounted) return;
      setState(() {
        default_categories.clear();
        Category all = new Category(
            label: "全部", selected: true, path: _module.id.toString(), id: 0);
        default_categories.add(all);
        default_categories.addAll(res.data);
      });
    });
  }

  void _getAll() {
    resources.clear();
    currentPage = 0;
    currentPath = _module.id.toString();
    currentFilter = "";
    currentCategoryLabel = "全部";
    initImageList();
    // _nextPage(currentPath, currentFilter);
  }

  // bool busy = false;
  // Timer _timer = null;

  void _nextPage(String path, String filter) {
    // if (busy) return;
    // busy = true;

    // LogUtil.d(StackTrace.current);
    ModuleApi().search(path, filter, currentPage, PAGE_SIZE).then((res) {
      // busy = false;
      // if (_timer != null)
      //   {
      //     _timer.cancel();
      //   }
      if (!this.mounted) return;
      setState(() {
        //这行代码很别扭，但是解决了可能是控件本身的一个bug，当不够一页数据时会重复加载两次
        if (resources.length < PAGE_SIZE && resources.length > 0) return;
        currentPage = res.data.pageIndex + 1;

        resources.addAll(res.data.list);
        _controller.finishLoad(success: true);
      });
    });
  }
  List<int> pageList=[];
  initImageList() {
    HashMap map=new HashMap();
    pageList=widget.info.curpages;
    for(int i = 0; i < pageList.length; i++) {
      map[i]=pageList.indexOf(i+1);
    }
    // LogUtil.d(map.toString());
    setState(() {
      for (int i = 0; i < totalPage; i++) {
        String url = baseUrl + "/" + (i+1).toString() + widget.info.ext;
        Resource res = new Resource(url: url, type: 0, id: widget.resource.id,page:(i+1));
        resources.add(res);
      }
    });
  }

  void on_categories_selected(Category category, double offset) {
    resources.clear();
    filterGroups.clear();
    currentPage = 0;
    currentPath = category.path;
    currentFilter = "";
    currentPid = category.id;
    currentCategoryLabel = category.label;
    currentCategory = category;
    currentScrollOffset = offset;
    // _nextPage(currentPath, currentFilter);
    _controller.callRefresh();
  }

  void request_with_filter(String path, String filter) {
    //String _filter = Uri.encodeComponent(filter);
    resources.clear();
    filterGroups.clear();
    currentPage = 0;
    currentPath = path;
    currentFilter = filter;
    currentPid = currentPid;
    // _nextPage(currentPath, currentFilter); //
    _controller.callRefresh();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    LogUtil.d("_ModuleStaggeredPageState initState");
    _getAll();
    // _get_default_categories();
  }

  @override
  void didChangeDependencies() {
    LogUtil.d("module_page didChangeDependencies");
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var width = MediaQuery.of(context).size.width * 0.88;
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
            iconTheme: IconThemeData(
              color: Colors.black54, //修改颜色
            ),
          toolbarHeight: getPortraitSHeight(50),
            automaticallyImplyLeading: true,
            leading: InkWell(child: Icon(Icons.arrow_back_ios),
            onTap: (){
              Navigator.of(context).pop();
            },) ,
            brightness: Brightness.light,
            title: Text(
              widget.resource.title,
              textAlign: TextAlign.center,
              style: TextStyle(color: text_black, fontSize: 15),
            ),
            backgroundColor: Colors.white,
            elevation: 1),
        body: Column(
          children: [
            SizedBox(height: getPortraitSHeight(8)),
            Expanded(child: _widget_grid()),
          ],
        ));
  }

  void showBottomModel() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        barrierColor: Colors.transparent,
        backgroundColor: Colors.white,
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(0), topRight: Radius.circular(0))),
        builder: (BuildContext context) {
          return SizedBox(
            // heightFactor: 0.88,
            height: getPortraitSHeight(550),
            child: ModuleGroupFilter(
              filterGroups: filterGroups,
              confirmPress: () => _confirmAction(),
            ),
          );
        });
  }

  void showMoreFilter() {
    ModuleApi().moreFilters(_module.id, currentPid, currentPath).then((res) {
      if (res.code == 200) {
        setState(() {
          filterGroups.clear();
          if (res.data.group_items != null) {
            MoreFilterGroup root = res.data;
            filterGroups.add(root);
            root.level = filterGroups.length;
          }
          showBottomModel();
        });
      }
    });
  }

  Widget getEmptyWidget() {
    return Text("");
  }

  Widget _widget_grid() {
    double width = MediaQuery.of(context).size.width * 0.98;
    ScrollController _scrollController = new ScrollController();
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      controller: _controller,
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        // currentPage = 0;
        // resources.clear();
        // _nextPage(currentPath, currentFilter);
      },
      onLoad: () async {
        // _nextPage(currentPath, currentFilter);
      },
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: RefreshIndicator(
            onRefresh: () async {
              await Future.delayed(Duration(seconds: 5));
            },
            child: Padding(
              padding: const EdgeInsets.only(top: 2, left: 4, right: 4),
              child: StaggeredGridView.countBuilder(
                shrinkWrap: true,
                controller: _scrollController,
                crossAxisCount: 3,
                crossAxisSpacing: 2,
                mainAxisSpacing: 2,
                itemCount: resources.length,
                itemBuilder: (context, index) {
                  var resource = resources[index];
                  // LogUtil.d("itemBuilder index>> $index");
                  return GridItemPhoto1(
                      url: resource.url,
                      width: width / 3,
                      index: index,
                      page: resource.page,
                      bgColor: Colors.white,
                      onTap: (_index){
                        LogUtil.d("===>tap:$_index");
                        BookPreview.JumpToPreview(
                            resource, context, false, resource.page-1);
                      });
                },
                staggeredTileBuilder: (index) => new StaggeredTile.count(1, 1.4),
              ),
            ),
            // (index) => new StaggeredTile.count(2, index==0?2.5:3)),
          ),
        ),
      ],
    );
  }

  resetAction() {
    setState(() {
      if (filterGroups.length > 0) {
        int c = filterGroups.length - 1;
        for (int i = 0; i < c; i++) {
          filterGroups.removeLast();
        }

        MoreFilterGroup g = filterGroups.first;
        for (int i = 0; i < g.group_items.length; i++) {
          g.group_items[i].selected = false;
        }
      }
    });
  }

  _confirmAction() {
    if (filterGroups.length > 0) {
      String path = "";
      String filter = "";
      String label = "";
      for (int i = filterGroups.length - 1; i >= 0; i--) {
        MoreFilterGroup mfg = filterGroups[i];
        if (mfg.asFilterObject) {
          for (int j = 0; j < mfg.group_items.length; j++) {
            if (mfg.group_items[j].selected) {
              filter += mfg.group_items[j].label;
              filter += "|";
              break;
            }
          }
        } else {
          for (int j = 0; j < mfg.group_items.length; j++) {
            if (mfg.group_items[j].selected) {
              path = mfg.group_items[j].path;
              break;
            }
          }
          if (path.isNotEmpty) break;
        }
      }
      //获取选中的label
      for (int i = 0; i < filterGroups.length; i++) {
        MoreFilterGroup mfg = filterGroups[i];
        for (int j = 0; j < mfg.group_items.length; j++) {
          if (mfg.group_items[j].selected) {
            label += mfg.group_items[j].label;
            label += "-";
            break;
          }
        }
      }
      if (filter.endsWith("|")) {
        filter = filter.substring(0, filter.length - 1);
      }
      if (label.endsWith("-")) {
        label = label.substring(0, label.length - 1);
      }
      LogUtil.d("label $label");
      setState(() {
        isFilter = true;
        if (currentCategoryLabel == "全部") {
          confirmKey = label;
        } else {
          confirmKey = (currentCategoryLabel + "-" + label);
        }
      });
      request_with_filter(path, filter);

      // ToastUtils.success(path + "~" + filter);
    }

    Navigator.of(context).pop();
  }
}
